package com.luxiu;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;

/**
 * 文件锁
 */
public class FileLock {
    public static void tryRead() throws IOException, InterruptedException, RuntimeException {
        File file = new File(App.class.getResource("/a.txt").getPath().substring(1));
        FileChannel channel = new FileOutputStream(file, true).getChannel();
        java.nio.channels.FileLock lock;
        synchronized (FileLock.class) {
            lock = channel.tryLock();
        }
        if (lock != null) {
            System.out.println("lock the file");
            Thread.sleep(1000000);
        } else {
            System.out.println("file has locked");
        }
    }

    public static void main(String[] args) {
        Runnable runnable = () -> {
            try {
                FileLock.tryRead();
            } catch (IOException | InterruptedException e) {
                System.out.println("error1: " + e.getMessage());
            } catch (Exception e) {
                System.out.println("error2: " + e.getLocalizedMessage());
            }
        };
        for (int i = 0; i < 2; i++) {
            Thread thread = new Thread(runnable);
            try {
                thread.join();
                thread.start();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

}
